//
//  AiSetViewModel.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/1/8.
//

import Foundation
import LeanCloud
import SwiftUI

/**
 *  ai 角色item
 */
class AiRoleItemViewModel : BaseViewModel {
    
    func doDelete(bean: AiRoleBean) {
        request {
            try check(!(bean.isSystem ?? false)) {
                "系统角色不能删除"
            }
            if !(bean.avatar ?? "").isEmpty {
                //删除图片
                try await retry(maxRetries: 10, retryDelayMillis: 200) {
                    _ = try await QiniuManager.shared.delete(url: bean.avatar ?? "", modeType: String.self)
                }
            }
            if !(bean.chatBg ?? "").isEmpty {
                //删除图片
                try await retry(maxRetries: 10, retryDelayMillis: 200) {
                    _ = try await QiniuManager.shared.delete(url: bean.chatBg ?? "", modeType: String.self)
                }
            }
            if !(bean.diaryBg ?? "").isEmpty {
                //删除图片
                try await retry(maxRetries: 10, retryDelayMillis: 200) {
                    _ = try await QiniuManager.shared.delete(url: bean.diaryBg ?? "", modeType: String.self)
                }
            }
            try await retry(maxRetries: 10, retryDelayMillis: 200) {
                _ = try await BackupsManager.shared.getDelegateConfig()?.delAiRole(bean: bean)
            }
            return true
        } suc: { _ in
            showToast("删除成功")
            TaskExt.deleteTask(bean.objectId) //删除角色任务
            NotificationCenter.default.post(name: .updateAiRole, object: true)
        } fail: {
            showToast($0.message)
        }
    }
    
    func selectAiRole(list: [AiRoleBean], suc: @escaping ()-> Void) {
        request {
            try await retry(maxRetries: 5, retryDelayMillis: 200) {
                let selectList : [AiRoleBean] = list.filter{ $0.select == true }
                try await BackupsManager.shared.getDelegateConfig()?.selectAiRole(list: selectList)
            }
            return true
        } suc: { _ in
            suc()
            NotificationCenter.default.post(name: .selectAiRole, object: true)
        } fail: {
            showToast($0.message)
        }
    }
    
    //设置常聊天
    func doSetOften(roleId: String?) {
        request(isLoading: false) {
            try await BackupsManager.shared.getDelegateConfig()?.setOften(roleId: roleId)
        } suc: {
            showToast("设置成功")
            NotificationCenter.default.post(name: .refreshHomeChat, object: true)
        } fail: {
            showToast($0.message)
        }
    }
}
